// base
import Taro, { Component } from '@tarojs/taro'
import { View, Text, ScrollView, Image } from '@tarojs/components'
// redux
import { connect } from '@tarojs/redux'
import { DOREQUESTCHOOSEDESIREJOB } from './store/actions/pagechoosedesirejob'
import { UPDATEPAGECHOOSEDESIREJOB } from './store/types/pagechoosedesirejob'
import { UPDATEBASEUSERINFO } from '../../store/types/baseuserinfo'
// less
import './index.less'

// componnet
import BtmFixedBtn from '../../components/page-components/btm-fixed-btn'
import { showToast } from '../../crossplatform/apiservice/toast'
import { navigateBack } from '../../crossplatform/apiservice/navigate'
import { UPDATEPAGEEDITJOBINTENTION } from '../edit-job-intention/store/types/pageeditjobintention'
import { getGlobalData } from '../../configuration/globaldata'
import {
  addCareerObjectiveRequest,
  deljobHuntingRequest,
  editCareerObjectiveRequest
} from '../../service/user-archive-controller'
import userinfo from '@/store';

const mapActiontoProps = dispatch => ({
  updateState(payload) {
    dispatch({
      type: UPDATEPAGECHOOSEDESIREJOB,
      payload: {
        ...payload
      }
    })
  },
  updateEditJobIntentionState(payload) {
    dispatch({
      type: UPDATEPAGEEDITJOBINTENTION,
      payload: {
        ...payload
      }
    })
  },
  dorequest(type) {
    return new Promise(() => {
      let promise = DOREQUESTCHOOSEDESIREJOB(type)
      dispatch(promise)
    })
  },
  updateBaseUserState(payload) {
    dispatch({
      type: UPDATEBASEUSERINFO,
      payload: {
        ...payload
      }
    })
  }
})

@connect(
  ({ pagechoosedesirejob, pageeditjobintention, baseuserinfo, userinfo }) => ({
    desireList: pagechoosedesirejob.desireList,
    workCategory: pageeditjobintention.workCategory,
    workNature: pageeditjobintention.workNature,
    baseuserinfo,
    userId: userinfo.userId
  }),
  mapActiontoProps
)
class ChooseDesireJob extends Component {
  config = {
    navigationBarTitleText: '求职意向',
    disableScroll: true
  }

  constructor(props) {
    super(props)
    this.state = {
      desireListSelect: [...props.workCategory].filter(e => e),
      leftSelectedIndex: 0
    }
  }

  componentWillMount() {
    // onLoad
  }

  componentDidMount() {
    // onready
  }

  componentDidShow() {
    // onshow
    this.queryWrap()
  }

  componentDidHide() {
    // onhide
  }

  componentWillUnmount() {
    // onUnload
  }

  queryWrap = () => {
    const { type, isBaseInfo } = this.$router && this.$router.params
    const { dorequest } = this.props
    dorequest(type)
    // 判断是否是基本信息进入
    this.setState({
      isBaseInfo
    })
  }

  getTypeByWorkNature = () => {
    const { workNature } = this.props
    const workNatureArr = getGlobalData('workNature')
    return workNatureArr.findIndex(item => {
      return item === workNature[0]
    })
  }

  render() {
    const { desireList } = this.props
    const { desireListSelect, leftSelectedIndex } = this.state

    return (
      <View className="ChooseDesireJob_id57777">
        <View className="top-title">
          <View className="title">
            <View className="title-text">期望职位</View>
            {/* <View className="title-btn" onClick={this.getSubmitData}>保存</View> */}
          </View>
          <View className="desc">*快来pick你心仪的职位吧，可选3个哦！</View>

          <View className="chosed-desire-list">
            {desireListSelect.map((item, index) => {
              return (
                <View key={index} className="chosed-desire-item">
                  <View className="item-text">{item}</View>
                  <View className="item-closed" onClick={this.deleteDesireItem.bind(this, item)}>
                    <Image
                      className="item-closed-img"
                      src="https://imagesize.hrwork.com/sp/files/661a184f-c34b-448d-bac9-c02972b1a48d.png"
                    />
                  </View>
                </View>
              )
            })}
          </View>
          <View className="desire-content">
            <ScrollView className="desire-left" scrollY>
              {desireList.map((item, index) => {
                return (
                  <View
                    key={index}
                    className="item-view"
                    onClick={this.leftSelect.bind(this, item, index)}
                  >
                    <Text
                      className={`item-view-name ${
                        leftSelectedIndex === index ? 'item-view-name-selected' : ''
                      }`}
                    >
                      {item.name}
                    </Text>
                    <View
                      className={`item-view-bottom-line ${
                        leftSelectedIndex === index ? 'item-view-bottom-line-selected' : ''
                      }`}
                    />
                  </View>
                )
              })}
            </ScrollView>
            <ScrollView className="desire-right" scrollY>
              {desireList &&
                desireList.length > 0 &&
                desireList[leftSelectedIndex].industryCategories &&
                desireList[leftSelectedIndex].industryCategories.map((item, index) => {
                  return (
                    <View
                      key={index}
                      className="item-view"
                      onClick={this.rightSelect.bind(this, item, index)}
                    >
                      <Text
                        className={`item-view-name ${
                          desireListSelect.includes(item.name) ? 'item-view-name-selected' : ''
                        }`}
                      >
                        {item.name}
                      </Text>
                      <View
                        className={`item-view-bottom-line ${
                          desireListSelect.includes(item.name)
                            ? 'item-view-bottom-line-selected'
                            : ''
                        }`}
                      />
                    </View>
                  )
                })}
            </ScrollView>
          </View>
        </View>
        <BtmFixedBtn text="完成" onTap={this.comfirm} />
      </View>
    )
  }

  deleteDesireItem = item => {
    const { desireListSelect } = this.state
    this.setState({
      desireListSelect: desireListSelect.filter(e => e !== item)
    })
  }

  leftSelect = (item, index) => {
    this.setState({
      leftSelectedIndex: index
    })
  }

  rightSelect = item => {
    let { desireListSelect } = this.state
    if (desireListSelect.length < 3) {
      if (desireListSelect.includes(item.name)) {
        desireListSelect = desireListSelect.filter(e => e !== item.name)
      } else {
        desireListSelect = [...desireListSelect, item.name]
      }
    } else {
      if (desireListSelect.includes(item.name)) {
        desireListSelect = desireListSelect.filter(e => e !== item.name)
      } else {
        showToast({
          title: '最多只能选择3个期望职位哦！'
        })
      }
    }
    this.setState({
      desireListSelect: [...desireListSelect]
    })
  }
  comfirm = () => {
    const { desireListSelect, isBaseInfo } = this.state
    const { updateEditJobIntentionState, baseuserinfo } = this.props
    if (desireListSelect.length <= 0) {
      showToast({
        title: '请至少选择一个期望职位'
      })
    } else {
      if (isBaseInfo) {
        // 从基本信息进入页面
        const { userInfoC } = baseuserinfo
        let jobIntention = { ...userInfoC.jobIntention }
        jobIntention.workCategory = [...desireListSelect]
        this.props.updateBaseUserState({
          userInfoC: {
            ...userInfoC,
            jobIntention
          }
        })
        // 点击完成
        this.onBaseInfoConfirm(jobIntention)
      } else {
        updateEditJobIntentionState({
          workCategory: [...desireListSelect]
        })
        navigateBack()
      }
    }
  }

  onBaseInfoConfirm = jobIntention => {
    // 点击完成
    const { workPlace, workNature, workCategory } = jobIntention
    if (workNature.length <= 0) {
      this.showToastMessage('请选择工作性质')
      return
    }
    if (workPlace.length <= 0) {
      this.showToastMessage('请选择工作区域')
      return
    }
    if (workCategory.length <= 0) {
      this.showToastMessage('请选择期望职位')
      return
    }
    this.addCareerObjective()
  }

  addCareerObjective = () => {
    const {
      wantWorkId,
      userId,
      baseuserinfo: { userInfoC }
    } = this.props
    const {
      archiveId,
      jobIntention: { jobCity, workPlace, workNature, workCategory }
    } = userInfoC

    const { isEdit } = this.$router && this.$router.params
    let comprehensive = JSON.stringify({
      workNature: Array.isArray(workNature[0]) ? workNature[0] : workNature,
      workPlace,
      workCategory
    })
    if (parseInt(isEdit) === 1) {
      editCareerObjectiveRequest({
        jobPlace: jobCity,
        comprehensive,
        id: wantWorkId,
        userId,
        archiveId,
        userName: userInfoC.userName
      }).then(({ data }) => {
        const { status, message } = data
        if (status) {
          navigateBack()
        } else {
          showToast({title: message || '更新失败'})
        }
      })
    } else {
      addCareerObjectiveRequest({
        jobPlace: jobCity,
        comprehensive,
        userId,
        archiveId,
        userName: userInfoC.userName,
        gmtCreate: new Date().getTime()
      }).then(({ data }) => {
        console.info(data)
        const { status, message } = data
        if (status) {
          navigateBack()
        } else {
          showToast({title: message || '添加失败'})
        }
      })
    }
  }
}

export default ChooseDesireJob
